package com.rzico.sbl.ui.report

import android.widget.CompoundButton
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportOrderSendBinding
import com.rzico.sbl.model.OrderData
import com.rzico.sbl.model.OrderShipData
import com.rzico.sbl.other.shopId
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportOrderViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.count
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter
import kotlin.text.orEmpty

class ReportOrderShipActivity : BaseActivity(R.layout.activity_report_order_send) {

    private val mBinding by lazy {
        ActivityReportOrderSendBinding.bind(getRootView())
    }

    override fun getViewModel() = get<ReportOrderViewModel>()

    private val mShipList = arrayListOf<OrderShipData>()

    override fun initData() {
        initTitle(title = "批量发货")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .shipAll
            .setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .also {
                        it.emptyImg.setEmptyImage(
                            resId = R.mipmap.icon_order_no,
                            dpSize = 100f
                        )
                        it.emptyHint.text = "暂无相关订单信息！"
                    }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            if (!isLoadingMore) {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<OrderData>(R.layout.item_report_batch) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_batch_time, bean.createDate.getTimeString())
                                text(R.id.item_batch_name, bean.consignee)
                                text(R.id.item_batch_phone, bean.phone)
                                text(R.id.item_batch_adress, bean.address)
                                text(R.id.item_batch_num, bean.sn)
                                text(R.id.item_batch_send, bean.sellerName)

                                image(
                                    R.id.item_batch_check,
                                    conditionIf(
                                        bean.check,
                                        R.mipmap.login_yes_orange,
                                        R.mipmap.login_no
                                    )
                                )

                                clicked(R.id.item_batch_check) {
                                    bean.check = !bean.check
                                    notifyItemChanged(index)

                                    checkAllSelected()
                                }

                                clicked(R.id.item_batch) {
                                    goToOrderDetail("orderSn" to bean.sn)
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            shipAll.oneTouch(handle = { mList.isEmpty() })
            shipAll.setOnCheckedChangeListener(this@ReportOrderShipActivity)

            shipClear.oneClick {
                if (mList.any { (it as OrderData).check }) {
                    mList.filter {
                        it as OrderData
                        it.check
                    }.forEach {
                        it as OrderData
                        it.check = false
                    }

                    mAdapter.notifyDataSetChanged()

                    checkAllSelected()
                }
            }

            shipSure.oneClick {
                mList.notEmpty {
                    when {
                        any { (it as OrderData).check } -> {
                            val idString = this
                                .filter { (it as OrderData).check }
                                .joinToString(",") { (it as OrderData).id }

                            if (mShipList.isEmpty())
                                getShipList { showSendDialog(idString) }
                            else showSendDialog(idString)
                        }

                        else -> showToast("请选择要发货的订单")
                    }
                }
            }
        }
    }

    /**
     * 全选点击事件监听
     */
    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach {
            it as OrderData
            it.check = isChecked
        }
        mAdapter.notifyDataSetChanged()

        mBinding.shipSure.text = "发货(${totalCount()})"
    }

    /**
     * 检查全选按钮状态
     */
    private fun checkAllSelected() {
        mBinding.apply {
            shipAll.setOnCheckedChangeListener(null)
            shipAll.isChecked =
                mList.isNotEmpty() and mList.none { !(it as OrderData).check }
            shipAll.setOnCheckedChangeListener(this@ReportOrderShipActivity)

            shipSure.text = "发货(${totalCount()})"
        }
    }

    /**
     * 选中数量
     */
    private fun totalCount() = mList.count { (it as OrderData).check }

    /**
     * 显示发货弹框
     */
    private fun showSendDialog(orderIds: String) {
        showListDialog(
            title = "请选择配送站",
            index = mShipList.indexOfFirst { it.id == shopId },
            items = mShipList.map { it.name },
            listener = { positon, _ ->
                getViewModel()
                    .requestBind(
                        requestUrl = ReportUrl.getBaseUrl().rptShipA,
                        params = arrayOf(
                            "ids" to orderIds,
                            "shopId" to mShipList[positon].id,
                            "shippingMethod" to "warehouse"
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("批量发货成功！")

                            updateList()

                            // 更新订单列表
                            LiveEventBus
                                .get("orderModify")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 获取配送站列表
     */
    private fun getShipList(onNext: () -> Unit) {
        getViewModel()
            .requestModel(
                isLoading = true,
                requestUrl = ReportUrl.getBaseUrl().rptWhere,
                requestMethod = HttpMethod.GET,
                onSuccess = { list ->
                    mShipList.clear()
                    list.mapTo(mShipList) {
                        OrderShipData(
                            it.id,
                            it.name.orEmpty(),
                            it.linkman.orEmpty(),
                            it.telephone.orEmpty()
                        )
                    }
                },
                onFinally = onNext
            )
    }

    /**
     * 批量发货列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .batchList(
                page = index,
                method = "shipping",
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    checkAllSelected()

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh
                                .isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh
                    .isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}